// import utils
import apiRequest from "./request.js";
import { formateDate, randomAppointments } from "@/common/utils.js"

/* --------------------------------------------------------------
 *                         Appointment API
 * -------------------------------------------------------------- */

/**
 * 审核访客申请记录
 * @param {Object} data - 更新的数据
 * @param {Array} tableData - 当前表格数据
 * @returns {Promise<Object>} - 修改后的表格数据
 */
async function updateAppointment(data, tableData) {
    try {
        // TODO 由于他的接口有问题，两个相同路径，所以调用不了
        // const response = await apiRequest('POST', `/appointment/UpdateAppointment`, data);
        const response = { code: 200, success: true };

        if (response.code === 200 && response.success) {
            const index = tableData.findIndex(item => item.id === data.id);
            if (index !== -1) {
                // 处理修改后的访客申请记录
                const updatedData = {
                    ...data,
                    updateTime: formateDate(new Date()),
                };

                // 将修改后的访客申请记录插入到表格数据中
                tableData.splice(index, 1, updatedData);

                return { success: true, data: tableData };
            } else {
                throw new Error('访客申请记录未找到');
            }
        } else {
            throw new Error('修改访客申请记录失败');
        }
    } catch (error) {
        console.error('修改访客申请记录失败:', error);
        throw new Error('修改访客申请记录失败');
    }
}


/**
 * 删除访客申请记录
 * @param {number} id - 访客申请记录 ID
 * @param {Array} tableData - 当前表格数据
 * @returns {Promise<Object>} - 删除后的表格数据 
 */
async function deleteAppointment(id, tableData) {
    try {
        const data = { id, isDel: 1 };
        // TODO 由于他的接口有问题，两个相同路径，所以调用不了
        // const response = await apiRequest('POST', '/appointment/UpdateAppointment', data);
        const response = { code: 200, success: true };

        if (response.code === 200 && response.success) {
            // 更新删除后的表格数据
            const updatedTableData = tableData.filter(item => item.id !== id);
            return { success: true, data: updatedTableData };
        } else {
            throw new Error('删除访客申请记录失败');
        }
    } catch (error) {
        console.error('删除访客申请记录失败:', error);
        throw new Error(error.message || '删除访客申请记录失败');
    }
}

/**
 * TODO 没有接口,暂时随机产生,需要替换
 * 查询访客申请记录列表
 * @param {Object} searchData - 查询表单数据
 * @param {Object} pageData - 分页数据
 * @returns {Promise} - Promise对象，包含查询结果
 */
async function searchAppointmentList(searchData, pageData) {
    try {
        // TODO 只有pageSize有用,其他没有效果，之后真实请求才有用
        const data = {
            name: searchData.name,
            status: searchData.status,
            professor: searchData.professor,
            startDate: searchData.dateRange[0],
            endDate: searchData.dateRange[1],
            pageNum: pageData.currentPage,
            pageSize: pageData.pageSize,
        }
        const appointments = randomAppointments(data.pageSize);
        const response = { success: true, code: 200, data: { list: appointments } }
        console.log(response)

        // 返回查询的访客申请记录列表
        if (response.code === 200 && response.success) {
            const transformedList = response.data.list.map((item, index) => ({
                id: item.id,
                userName: item.userName || "未知",
                status: item.status,
                createTime: formateDate(item.createTime) || "未知",
                updateTime: formateDate(item.updateTime) || "未知",
                appointmentTime: formateDate(item.appointmentTime) || "未知",
                appointmentContent: item.appointmentContent || "未知",
                userId: item.userId || "未知",
                userTel: item.userTel || "未知",
                userSfz: item.userSfz || "未知",
                userUnite: item.userUnite,
                professorId: item.professorId || "未知",
                professorName: item.professorName || "未知",
                isDel: item.isDel,
                type: item.type || "未知"
            }));
            return { success: true, data: transformedList }
        } else {
            throw new Error('查询访客申请记录失败');
        }

    } catch (error) {
        console.error('查询访客申请记录失败:', error);
        throw new Error(error.message || '查询访客申请记录失败');
    }
}

export {
    updateAppointment,
    deleteAppointment,
    searchAppointmentList,
};
